home *** CD-ROM | disk | FTP | other *** search
/ The Very Best of Atari Inside / The Very Best of Atari Inside 1.iso / mint / mntlb20 / lib / ttyname.c < prev    next >
C/C++ Source or Header  |  1991-12-06  |  2KB  |  90 lines

  1. /*
  2.  * ttyname -- figure out the name of the terminal attached to a file
  3.  * descriptor
  4.  *
  5.  * Written by Eric R. Smith and placed in the public domain.
  6.  */
  7.  
  8. #include <sys/types.h>
  9. #include <stat.h>
  10. #include <dirent.h>
  11. #include <string.h>
  12.  
  13. extern int __mint;
  14.  
  15. /* magic number alert! */
  16. static char tname[32];
  17.  
  18. /* Find the file in directory "dir" that matches "sbuf". Returns 1
  19.  * on success, 0 on failure. Note that "dir" is a prefix, i.e. it
  20.  * should end with "/".
  21.  */
  22.  
  23. static int
  24. find_ino(dir, sb, name)
  25.     char *dir;
  26.     struct stat *sb;
  27.     char *name;
  28. {
  29.     char *where = name;
  30.     DIR *drv;
  31.     struct dirent *next;
  32.     struct stat testsb;
  33.  
  34.     drv = opendir(dir);
  35.     if (!drv) return 0;
  36.  
  37.     while (*dir) {
  38.         *where++ = *dir++;
  39.     }
  40.  
  41.     while (next = readdir(drv)) {
  42.         strcpy(where, next->d_name);
  43.         if (stat(name, &testsb))
  44.             continue;
  45.         if (testsb.st_dev == sb->st_dev &&
  46.             testsb.st_ino == sb->st_ino) {
  47.             closedir(drv);
  48.             return 1;
  49.         }
  50.     }
  51.     closedir(drv);
  52.     return 0;
  53. }
  54.  
  55. char *
  56. ttyname(fd)
  57.     int fd;
  58. {
  59.     char *name;
  60.     struct stat sb;
  61.     extern int isatty();
  62.  
  63.     if (!isatty(fd)) return (char *)0;
  64.  
  65.     if (__mint < 9) {
  66.         if (fd == -2) {
  67.             name = "/dev/aux";
  68.         } else {
  69.             name = "/dev/con";
  70.         }
  71.         strcpy(tname, name);
  72.         return tname;
  73.     }
  74.  
  75.     if (fstat(fd, &sb))
  76.         return (char *)0;
  77.  
  78.     /* try the devices first */
  79.     if (find_ino("/dev/", &sb, tname))
  80.         return tname;
  81.  
  82.     /* hmmm, maybe we're a pseudo-tty */
  83.     if (find_ino("u:/pipe/", &sb, tname))
  84.         return tname;
  85.  
  86.     /* I give up */
  87.     strcpy(tname, "/dev/tty");
  88.     return tname;
  89. }
  90.